import {
  Router
} from "../../utils/common.js";
Page({
  data: {
    openid: '',
    userInfo: {},
    loading: true,
    petList: [],
    loadProgress: 0
  },
  onShow: function () {
    this.getOpenid();
  },
  /**
   * 获得运动步数
   */
  getWeRunData: function () {
    let that = this;
    wx.getWeRunData({
      success(res) {
        // 拿 encryptedData 到开发者后台解密开放数据
        const encryptedData = res.encryptedData
        // 或拿 cloudID 通过云调用直接获取开放数据
        const cloudID = res.cloudID
        // console.log(cloudID);
        //云函数获取微信步数
        wx.cloud.callFunction({
          name: 'getWxRun',
          data: {
            weRunData: wx.cloud.CloudID(cloudID), // 这个 CloudID 值到云函数端会被替换
          },
          success: function (data1) {
            if (data1.errMsg.includes('ok')) {
              let result = data1.result.event.weRunData.data;
              // that.setData({ stepInfoList: result.stepInfoList});
              // 保存用户微信步数
              let stepInfoList = result.stepInfoList;
              that.saveWxRun(stepInfoList);
            }
          },
          fail: res => {
            console.log('callFunction test result: ', res)
          }
        })
      },
      fail() {
        wx.showModal({
          title: '警告',
          content: '同意授权啦小火鸡!',
          showCancel: false,
          confirmText: '返回授权',
          success: function (res) {
            if (res.confirm) {
              this.getWeRunData();
            }
          }
        })
      }
    });

  },
  // 获取用户openid
  getOpenid() {
    let that = this;
    wx.cloud.callFunction({
      name: 'getOpenid',
      complete: res => {
        // console.log('云函数获取到的openid: ', res.result.openid)
        var openid = res.result.openid;
        that.setData({
          openid: openid
        });
        wx.setStorageSync('openid', this.data.openid);
        that.onQuery();
      }
    })
  },

  // 查询用户是否注册
  onQuery: function () {
    const db = wx.cloud.database();
    db.collection('p_user').where({
      _openid: this.data.openid
    }).get({
      success: res => {
        if (res.data.length > 0) {
          // console.log('[数据库] [查询记录] 成功: ', res.data)
          wx.setStorageSync('openid', this.data.openid);
          wx.setStorageSync('isLogin', true);
          // 保存用户信息
          this.setData({
            userInfo: res.data[0]
          })
          wx.setStorageSync('userInfo', res.data[0]);
          // 用户已注册  获取用户宠物列表
          this.getMyPetList();
          // 判断用户今天是否保存步数
          this.userIsSaveRun();

        } else {
          this.navToPetAddPre()
          wx.setStorageSync('isLogin', false);
        }
      },
      fail: err => {
        this.navToPetAddPre()
        console.log('[数据库] [查询记录] 失败：');
      }
    })
  },

  /**
   * 用户是否保存运动步数
   */
  userIsSaveRun() {
    let that = this;
    // 获取当前年月日
    var date = new Date();
    var myDate = date.toLocaleDateString(); //获取当前日期
    const db = wx.cloud.database();
    db.collection('p_user').where({
      _openid: wx.getStorageSync('openid'),
      modifyTime: this.getNextDate(myDate, 0)
    }).get({
      success: res => {
        if (res.data.length > 0) {
          console.log("已保存");
        } else {
          // console.log("未保存");
          // 获取用户微信运动步数
          that.getWeRunData();
        }
      },
      fail: err => {
        console.log('[数据库] [查询记录] 失败：')
      }
    })
  },
  /**
   * 保存微信步数
   */
  saveWxRun(stepInfoList) {
    // 获取当前年月日
    let date = new Date();
    let myDate = date.toLocaleDateString(); //获取当前日期
    let ymd = this.getNextDate(myDate, 0); // 当前年月日
    let yesterday = this.getNextDate(myDate, -1);
    let step = 0; //运动步数
    for (let i = 0; i < stepInfoList.length; i++) {
      let timestamp = this.formatDate(stepInfoList[i].timestamp * 1000);
      console.log(timestamp);
      if (timestamp == yesterday) {
        step = stepInfoList[i].step; // 获取昨天运动步数
        // console.log(step);
        // console.log(this.data.userInfo._id);
        // 更新用户微信运动步数
        const db = wx.cloud.database();
        db.collection('p_user').doc(this.data.userInfo._id).update({
          data: {
            modifyTime: ymd,
            step: step
          }
        }).then(res => {
          console.log(res)
        })

      }
    }

  },
  //时间戳转换方法    date:时间戳数字
  formatDate(date) {
    var date = new Date(date);
    var YY = date.getFullYear() + '-';
    var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
    var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    return YY + MM + DD;
    // return YY + MM + DD + " " + hh + mm + ss;
  },
  // 转换日期
  getNextDate(date, day) {
    var dd = new Date(date);
    dd.setDate(dd.getDate() + day);
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
    var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
    return y + "-" + m + "-" + d;
  },
  getMyPetList: function () {
    this.loadProgress()
    const db = wx.cloud.database();
    db.collection('p_pets').where({
      _openid: wx.getStorageSync("openid")
    }).get({
      success: res => {
        if (res.data.length > 0) {
          this.setData({
            petList: res.data,
            loadProgress:100
          })
        }
      },
      fail: err => {
        console.log('[数据库] [查询记录] 失败：');
      }
    })
  },
  navToPetDet: function (e) {
    let params = {
      petId: e.currentTarget.dataset.petid
    }
    Router.navigateTo("../dogdet/dogdet", params);
  },
  navToPetAddPre: function () {
    Router.navigateTo("../dogaddpre/dogaddpre");
  },
  loadProgress() {
    this.setData({
      loadProgress: this.data.loadProgress + 3
    })
    if (this.data.loadProgress < 100) {
      setTimeout(() => {
        this.loadProgress();
      }, 100)
    } else {
      this.setData({
        loadProgress: 0
      })
    }
  }
})